package com.sunsun_china.www.aq.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 赵武 on 2015/7/3.
 * 服务器信息读取功能
 */
public class ServerInfoRead {

	public final static String RUL_READ = "http://121.43.235.47/post/read.php";
	public final static String RUL_WRITE = "http://121.43.235.47/post/write.php";
	public final static String RUL_UPDATE = "http://121.43.235.47/post/update.php";
	public final static String RUL_READ_LIST = "http://121.43.235.47/post/readlist.php";
	public final static String RUL_DELETE = "http://121.43.235.47/post/delete.php";
	public String mAC;
	public MyApplication mApp;

	public ServerInfoRead(MyApplication app) {
		mApp = app;
	}

	private List<String> toList(String json) {
		if (json == null) {
			return null;
		}
		if (json.length() == 0) {
			return null;
		}
		List<String> list = JSON.parseArray(json, String.class);
		return list;
	}

	public void read(String did, ServerInfoCallback cb) {
		final ServerInfoCallback final_cb = cb;
		final String final_did = did;
		mAC = getAC();
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				// 填充业务报文内容
				String par = "did=" + final_did + "&ac=" + mAC;
				// POST
				final String rtString = HttpUtils.sendPostUrl(RUL_READ, par, "UTF-8", "application/x-www-form-urlencoded");
				// 跨线程返回
				mApp.mHandler.post(new Runnable() {
					@Override
					public void run() {
						List<String> list = toList(rtString);
						if (list != null) {
							if (list.size() > 0) {
								Map<String, String> map = JSON.parseObject(list.get(0), new TypeReference<Map<String, String>>() {
								});
								if (map != null) {
									String comment = map.get("COMMENT");
									final_cb.callback(comment);
									return;
								}
							}
						}
						final_cb.callback(null);
					}
				});
			}
		});
		t.start();
	}

	private String getAC() {
		Calendar c = Calendar.getInstance();
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		String s = String.format("%1$02d%2$02d", day, hour);
		String md5 = MD5.get32Lowercase(s.getBytes());
		return md5;
	}

}
